package ext.generic.wfaugment.processors;

import java.beans.PropertyVetoException;
import java.io.Externalizable;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.util.misc.NmURL;
import com.ptc.netmarkets.work.NmWorkItemCommands;
import com.ptc.netmarkets.workflow.NmWorkflowHelper;

import ext.drawing.BorrowUtil;
import ext.drawing.BorrowWorkflowUtil;
import ext.drawing.HolidayUtil;
import ext.drawing.bean.DrawingsBorrowBean;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.part.PartWorkflowUtil;
import ext.tianma.bom.util.IBAUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.PartCommands;
import ext.tianma.upload.MyUtil;
import ext.tianma.workflow.WorkItemHelper;
import ext.workflow.WfActivityCompleteEvent;
import ext.workflow.WorkFlowUtil;
import wt.change2.ChangeHelper2;
import wt.change2.Changeable2;
import wt.change2.WTChangeActivity2;
import wt.change2.WTChangeOrder2;
import wt.content.ApplicationData;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectNoLongerExistsException;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.fc.collections.WTCollection;
import wt.fc.collections.WTValuedHashMap;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.pom.Transaction;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.team.Team;
import wt.team.TeamHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.engine.WfVariable;
import wt.workflow.engine.WfVotingEventAudit;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;
import wt.workflow.work.WorkflowHelper;

public class CmWorkItemCommands extends com.ptc.netmarkets.work.NmWorkItemCommands implements Externalizable {
	private static final boolean VERBOSE;
	private static final String RESOURCE = "com.ptc.netmarkets.work.workResource";
	private static final String CLASSNAME = CmWorkItemCommands.class.getName();
	// public static final NmWorkItemService service = new
	// NmWorkItemServiceFwd();
	static final long serialVersionUID = 1L;
	public static final long EXTERNALIZATION_VERSION_UID = 0xd4b6b5eeea339daL;
	protected static final long OLD_FORMAT_VERSION_UID = 0x2c663a688303ae3eL;
	private static final Logger logger;
	public static final String WI_TO_CONT = "WI_TO_CONT";
	public static final String ROUTER_EVENT = "WfUserEvent";
	public static final String ROUTER_LIST = "WfUserEventList";
	public static final String COMMENTS = "comments";
	public static final String ACTIVITY_VAR = "WfActVar";
	public static final String CUSTOM_ACTIVITY_VAR = "CustActVar";
	public static final String ROUTER_CHECK = "WfRouterCheck";
	public static final String ESIG = "WfESignature";
	public static final String VOTE_ACTION = "voteAction";
	public static final String ESIGPASSWD = "signatureEngine_password";
	public static final String ESIGUSER = "signatureEngine_username";
	public static final String ASSIGN_TO = "assignTo";
	public static final String ASSIGN_COMMENTS = "assignComments";
	public static final String AUTOMATE_FAST_TRACK = "automateFastTrack";
	public static final ArrayList ASSIGNMENTS_LIST = null;
	public static final String DEADLINE = "deadline";
	public static final String TASK_KEY = "tk";
	public static final String MY_TASKS = "my";
	public static final String PROJECT_TASKS = "prj";
	public static final String PRODUCT_TASKS = "prd";
	public static final String LIBRARY_TASKS = "lib";
	public static final String PLAN_TASKS = "pln";
	public static final String DETAILS_TASKS = "dtl";
	public static final String VIEW_DOCUMENT = "viewDocument";
	public static final String OVERVIEW_TASKS = "orv";
	public static final String TASK_OID = "task-oid";
	public static final String TASK_TYPE = "task-type";
	public static final String ASSIGNMENT_IMAGE = "ASSIGNMENT_IMAGE";
	public static final String ASSIGNMENT_REASSIGNED = "ASSIGNMENT_REASSIGNED";
	public static final String PBO_TYPEICON = "PBO_TYPEICON";
	public static final String ASSIGNMENT_NAME = "ASSIGNMENT_NAME";
	public static final String ASSIGNMENT_ROWACTIONS = "ASSIGNMENT_ROWACTIONS";
	public static final String ASSIGNMENT_SUBJECT = "ASSIGNMENT_SUBJECT";
	public static final String ASSIGNMENT_OBJECT = "ASSIGNMENT_OBJECT";
	public static final String ASSIGNMENT_SUBJECT_LC_STATE = "ASSIGNMENT_SUBJECT_LC_STATE";
	public static final String ASSIGNMENT_DEADLINE = "ASSIGNMENT_DEADLINE";
	public static final String ASSIGNMENT_PERCENT_DONE = "ASSIGNMENT_PERCENT_DONE";
	public static final String ASSIGNMENT_STATUS = "ASSIGNMENT_STATUS";
	public static final String ASSIGNMENT_CREATED = "ASSIGNMENT_CREATED";
	public static final String ASSIGNMENT_OWNER = "ASSIGNMENT_OWNER";
	public static final String ASSIGNMENT_CONTAINER = "ASSIGNMENT_CONTAINER";
	public static final String ASSIGNMENT_ROLE = "ASSIGNMENT_ROLE";
	public static final String ASSIGNMENT_CREATED_BY = "ASSIGNMENT_CREATED_BY";
	public static final String ASSIGNMENT_IS_OVERDUE = "ASSIGNMENT_IS_OVERDUE";
	public static final String ASSIGNMENT_IS_ASSIGNED_TO_ME = "ASSIGNMENT_IS_ASSIGNED_TO_ME";
	public static final String ASSIGNMENT_IS_CREATED_BY_ME = "ASSIGNMENT_IS_CREATED_BY_ME";
	public static final String OPEN_ASSIGNMENTS = "OPEN_ASSIGNMENTS";
	public static final String WORKITEM_TYPE = "WORKITEM_TYPE";
	public static final String WORKITEM_STATUS = "workItemStatus";
	public static final String DISCUSSED = "DISCUSSED";
	public static final String TABLE_ID = "TABLE_ID";
	public static final String TABLE_VIEW_ID = "TABLE_VIEW_ID";
	public static final String HOME_WORKLIST = "HOME_WORKLIST";
	public static final String HOME_WORKLIST_TABLE_ID = "netmarkets.assignments.list";
	public static final String HOME_OVERVIEW_WORKLIST = "HOME_OVERVIEW_WORKLIST";
	public static final String HOME_OVERVIEW_WORKLIST_TABLE_ID = "netmarkets.overview.assignments.list";
	public static final String PLAN_HOME_OVERVIEW_WORKLIST_TABLE_ID = "projectmanagement.overview.assignments.list";
	public static final String PROJECT_WORKLIST = "PROJECT_WORKLIST";
	public static final String PROJECT_WORKLIST_TABLE_ID = "netmarkets.project.assignments.list";
	public static final String PLAN_WORKLIST_TABLE_ID = "projectmanagement.plan.assignments.list";
	public static final String PRODUCT_WORKLIST = "PRODUCT_WORKLIST";
	public static final String PRODUCT_WORKLIST_TABLE_ID = "netmarkets.product.assignments.list";
	public static final String LIBRARY_WORKLIST = "LIBRARY_WORKLIST";
	public static final String LIBRARY_WORKLIST_TABLE_ID = "netmarkets.library.assignments.list";
	public static final String CHANGE_WORKLIST_TABLE_ID = "netmarkets.change.assignments.list";
	public static final String LIST_TYPE = "LIST_TYPE";
	public static final String WfAATOWI_KEY = "WfAATOWI_KEY";
	public static final String CONTAINER_MAP = "CONTAINER_MAP";
	public static final String CURRENT_CONTAINER = "CURRENT_CONTAINER";
	public static final String EXT_PARTICIPANT_MAP = "EXT_PARTICIPANT_MAP";
	public static final String WORKLIST_TABLE_USE_MORE = "WORKLIST_TABLE_USE_MORE";
	public static final String WORKLIST_TABLE_HIDE_ROLE_COL = "WORKLIST_TABLE_HIDE_ROLE_COL";
	public static final String WORKLIST_TABLE_REPLACE_ROLE_WITH_CREATOR = "WORKLIST_TABLE_REPLACE_ROLE_WITH_CREATOR";
	public static final String SUBMIT_TASK_ACTION = "submit";
	public static final String REVIEW_TASK_ACTION = "review";
	public static final String PROMOTE_TASK_ACTION = "promote";
	public static final String VOTE = "vote";

	// customization NO.0 begin
	public static final WfAugmentService custService = new ext.generic.wfaugment.processors.WfAugmentServiceFwd();
	public static WTArrayList reviewObjss = new WTArrayList();

	// customization NO.0 end

	public CmWorkItemCommands() {
	}

	public static FormResult complete(NmCommandBean nmcommandbean) throws WTException {
		System.out.println("============complete start========");
		
		testComments(nmcommandbean);

		// sqe审核上传多个文档 2019年1月16日
		uploadFiles(nmcommandbean);

		// 填写半成品正式编码 start
		//editNumber(nmcommandbean);
		// end

		NmURL nmurl = new NmURL();
		/**
		 * EE代码流程 参与者模块
		 */
		HttpServletRequest request = nmcommandbean.getRequest();
		String roleAndUser = request.getParameter("roleAndUser");

		if (!"".equals(roleAndUser) && null != roleAndUser) {
			try {
				WfActivityCompleteEvent.doEE(nmcommandbean);
				return NmWorkItemCommands.complete(nmcommandbean);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new WTException(e);
			}

		}
		// ;
		System.out.println("wo wan cheng ren wu");

		// add by lilin 2018年11月27日23:07:41
		String topDocDay = request.getParameter("day");
		String ver = request.getParameter("docVer");
		if (topDocDay != null || ver != null) {
			try {
				doDrawingPDF(nmcommandbean);
				return NmWorkItemCommands.complete(nmcommandbean);
			} catch (Exception e) {
				e.printStackTrace();
				throw new WTException(e);
			}
		}
		if (VERBOSE)
			System.out.println("=> CmWorkItemCommands.complete（）");
		Vector vector = null;
		String s = null;
		Enumeration enumeration = nmcommandbean.getRequest().getParameterNames();
		boolean flag = false;
		// customization NO.1 begin
		String participants = "";
		boolean custWfAugment = false;
		// customization NO.1 end

		do {
			if (!enumeration.hasMoreElements()) {
				break;
			}
			String s1 = (String) enumeration.nextElement();
			String s2 = NmCommandBean.convert(s1);
			if (logger.isTraceEnabled()) {
				logger.trace((new StringBuilder()).append("=> NmWorkItemCommands.complete: ").append(s2).append(", ")
						.append(nmcommandbean.getTextParameter(s1)).toString());
			}
			if (s2.indexOf("WfUserEvent") >= 0 && s2.lastIndexOf("old") == -1) {
				String s3 = null;
				if (s2.indexOf("WfRouterCheck") >= 0) {
					s3 = s2.substring(s2.indexOf("WfRouterCheck") + "WfRouterCheck".length(), s2.lastIndexOf("___"));
				} else {
					s3 = nmcommandbean.getTextParameter(s1);
				}
				if (vector == null) {
					vector = new Vector();
				}
				vector.addElement(s3);
			} else if (s2.indexOf("CustActVar") >= 0 && !s2.endsWith("old")) {
				int i = s2.indexOf("CustActVar") + "CustActVar".length();
				int j = s2.lastIndexOf("CustActVar");
				nmcommandbean.getMap().put(s2.substring(i, j), nmcommandbean.getTextParameter(s1));
			} else if (s2.indexOf("voteAction") >= 0 && s2.lastIndexOf("old") == -1) {
				nmcommandbean.getMap().put("voteAction", nmcommandbean.getTextParameter(s1));
			} else if (s2.indexOf("signatureEngine_password") >= 0 && !s2.endsWith("old")) {
				nmcommandbean.getMap().put("signatureEngine_password", nmcommandbean.getTextParameter(s1));
			} else if (s2.indexOf("signatureEngine_username") >= 0 && !s2.endsWith("old")) {
				nmcommandbean.getMap().put("signatureEngine_username", nmcommandbean.getTextParameter(s1));
			} else if (s2.indexOf("___comments___") >= 0 && !s2.endsWith("___old")) {
				s = nmcommandbean.getTextParameter(s1);
			} else if (s2.indexOf("___automateFastTrack___automateFastTrack") >= 0) {
				HashMap hashmap = nmcommandbean.getChecked();
				if (hashmap != null) {
					Object obj = hashmap.get("automateFastTrack");
					if (obj != null && (obj instanceof ArrayList)) {
						ArrayList arraylist = (ArrayList) obj;
						String s5 = (String) arraylist.get(0);
						if (s5 != null && s5.equals("automateFastTrack")) {
							flag = true;
						}
					}
				}
				if (logger.isTraceEnabled()) {
					logger.trace((new StringBuilder()).append("NmWorkItemCommands.complete: auto create ECN: ")
							.append(flag).toString());
				}
			}

			// customization NO.2 begin
			else if (s2.equals("RolesParticipants")) {
				if (VERBOSE)
					System.out.println("=> CmWorkItemCommands.complete: enter getting RolesParticipants...");
				participants = nmcommandbean.getTextParameter(s1);
				custWfAugment = true;
			}
			// customization NO.2 end
		} while (true);

		// customization NO.3 begin
		if (custWfAugment)
			custService.save(nmcommandbean, participants);
		// customization NO.3 end
		if (s == null || s != null && s.trim().length() == 0) {
			s = " ";
		}
		nmcommandbean.getMap().put("automateFastTrack", String.valueOf(flag));
		if (logger.isTraceEnabled()) {
			logger.trace((new StringBuilder()).append("   comments = ").append(s).toString());
		}
		nmcommandbean.getMap().put("WfUserEventList", vector);
		nmcommandbean.getMap().put("comments", s);
		HttpServletRequest httpservletrequest = nmcommandbean.getRequest();
		HttpSession httpsession = nmcommandbean.getRequest().getSession();
		HashMap hashmap1 = (HashMap) httpsession.getAttribute("CHECKED_USERS");
		if (hashmap1 != null) {
			Boolean boolean1 = (Boolean) httpsession.getAttribute("isPaged");
			if (boolean1 != null && !boolean1.booleanValue()) {
				nmcommandbean.getMap().put("isPaged", "false");
			}
			HashMap hashmap2 = nmcommandbean.getOldChecked();
			HashMap hashmap3 = nmcommandbean.getChecked();
			for (Iterator iterator = hashmap2.keySet().iterator(); iterator.hasNext();) {
				Object obj1 = iterator.next();
				if (!hashmap3.containsKey(obj1)) {
					hashmap1.remove(obj1);
				} else {
					hashmap2.put(obj1, hashmap3.get(obj1));
					hashmap1.put(obj1, hashmap2.get(obj1));
				}
			}

			HashMap hashmap4 = nmcommandbean.getUnChecked();
			Object obj2;
			for (Iterator iterator1 = hashmap4.keySet().iterator(); iterator1.hasNext(); hashmap1.remove(obj2)) {
				obj2 = iterator1.next();
			}
			hashmap1.remove("ROLE_MAP");
			hashmap3.putAll(hashmap1);
			nmcommandbean.setChecked(hashmap3);
		}
		// add by wzhou
		String supplier = null;
		String price = null;
		String currency = null;
		String delivery = null;
		String landt = null;
		String order = null;
		String minpackage = null;
		boolean typeflag = true;
		boolean typeflag1 = true;
		// WfActivity wfactivity1 = null;
		boolean flag1 = false;
		flag1 = isReject(nmcommandbean);
		if (custWfAugment == false) {
			// setProcessVariable(nmcommandbean);
			NmOid nmoid = nmcommandbean.getPrimaryOid();
			WorkItem workitem2 = (WorkItem) nmoid.getRef();
			wt.fc.Persistable pbo = workitem2.getPrimaryBusinessObject().getObject();
			// typeflag =
			// ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject)pbo,"F1")||ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject)pbo,"F7")||ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject)pbo,"FA");
			typeflag = ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "CF")
					|| ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "RawMaterial")
					|| ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "Polarizer")
					|| ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "PhantomPolarizer");
			typeflag1 = ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "C4");
			// ProcessData workitemProcessData = workitem2.getContext();
			WfActivity wfactivity1 = (WfActivity) workitem2.getSource().getObject();
			System.out.println("当前活动的名称：" + wfactivity1.getName());
			if (flag1) {
				if (wfactivity1.getName().equals("原材料审核信息输入") || (wfactivity1.getName().equals("半成品审核信息输入") && typeflag)
						|| (wfactivity1.getName().equals("二供物料审核信息输入") && typeflag)
						|| wfactivity1.getName().equals("版本进阶物料审核信息输入")) {
					// WfProcess wfprocess = wfactivity1.getParentProcess();
					// ProcessData wfprocessProcessData =
					// wfprocess.getContext();
					String emptyStr = "";
					String numberStr = "";
					HashMap aMap = nmcommandbean.getComboBox();
					HashMap textMap = nmcommandbean.getText();
					supplier = (String) textMap.get("supplier");
					if (null == supplier || supplier.trim().equals("")) {
						// throw new WTException("供应商字段不能为空，请填写!");
						emptyStr = emptyStr + "供应商字段" + ",";
					}
					price = (String) textMap.get("price");
					if (null == price || price.trim().equals("")) {
						// throw new WTException("价格字段不能为空，请填写!");
						emptyStr = emptyStr + "价格字段" + ",";
					} else {
						if (!PartCommands.isDecimal(price)) {
							numberStr = numberStr + "价格字段" + ",";
						}
					}
					/*
					 * if(!PartCommands.isDecimal(price)) { throw new WTException("价格字段，请填写!"); }
					 */
					currency = null;
					ArrayList<String> currencyList = (ArrayList<String>) aMap.get("currency");
					if (currencyList != null && currencyList.size() == 1) {
						currency = currencyList.get(0).trim();
					}
					if (null == currency || currency.trim().equals("")) {
						// throw new WTException("币种字段不能为空，请填写!");
						emptyStr = emptyStr + "币种字段" + ",";
					}

					delivery = (String) textMap.get("delivery");
					if (null == delivery || delivery.trim().equals("")) {
						emptyStr = emptyStr + "日交货能力字段" + ",";
						// throw new WTException("日交货能力字段不能为空，请填写!");
					} else {
						if (!PartCommands.isDecimal(delivery)) {
							numberStr = numberStr + "日交货能力字段" + ",";
						}
					}

					landt = (String) textMap.get("landt");
					if (null == landt || landt.trim().equals("")) {
						emptyStr = emptyStr + "L/T字段" + ",";
						// throw new WTException("L/T字段不能为空，请填写!");
					} else {
						if (!PartCommands.isDecimal(landt)) {
							numberStr = numberStr + "L/T字段" + ",";
						}
					}
					order = (String) textMap.get("order");
					if (null == order || order.trim().equals("")) {
						emptyStr = emptyStr + "最小订货量字段" + ",";
						// throw new WTException("最小订货量字段不能为空，请填写!");
					} else {
						if (!PartCommands.isDecimal(order)) {
							numberStr = numberStr + "最小订货量字段" + ",";
						}
					}

					minpackage = (String) textMap.get("minpackage");
					if (null == minpackage || minpackage.trim().equals("")) {
						emptyStr = emptyStr + "最小包装字段" + ",";
						// throw new WTException("最小包装字段不能为空，请填写!");
					} else {
						if (!PartCommands.isDecimal(minpackage)) {
							numberStr = numberStr + "最小包装字段" + ",";
						}
					}
					System.out.println("检查为空字段：" + emptyStr);
					System.out.println("检查数字字段：" + numberStr);
					if (!emptyStr.equals("")) {
						throw new WTException(emptyStr + "不能为空！");
					}
					if (!numberStr.equals("")) {
						throw new WTException(numberStr + "必须为数字！");
					}
					System.out.println("供应商：" + supplier);
					System.out.println("价格：" + price);
					System.out.println("币种：" + currency);
					System.out.println("日交货能力：" + delivery);
					System.out.println("L/T：" + landt);
					System.out.println("最小订货量：" + order);
					System.out.println("最小包装：" + minpackage);

					/*
					 * workitemProcessData.setValue("supplier", supplier);
					 * workitemProcessData.setValue("price", price);
					 * workitemProcessData.setValue("currency", currency);
					 * workitemProcessData.setValue("delivery", delivery);
					 * workitemProcessData.setValue("landt", landt);
					 * workitemProcessData.setValue("order", order);
					 * workitemProcessData.setValue("minpackage", minpackage);
					 * 
					 * workitem2.setContext(workitemProcessData);
					 * wt.fc.PersistenceHelper.manager.save(workitem2);
					 */

				}
				if ((wfactivity1.getName().equals("二供物料审核信息输入") || wfactivity1.getName().equals("半成品审核信息输入"))
						&& (!typeflag) && (!typeflag1)) {
					String emptyStr = "";
					String numberStr = "";
					HashMap aMap = nmcommandbean.getComboBox();
					HashMap textMap = nmcommandbean.getText();
					System.out.println(">>>>>>>>>>>>>>>>>>>>>>>2");
					price = (String) textMap.get("price");
					if (null == price || price.trim().equals("")) {
						// throw new WTException("价格字段不能为空，请填写!");
						emptyStr = emptyStr + "价格字段" + ",";
					} else {
						if (!PartCommands.isDecimal(price)) {
							numberStr = numberStr + "价格字段" + ",";
						}
					}
					if (!emptyStr.equals("")) {
						throw new WTException(emptyStr + "不能为空！");
					}
					if (!numberStr.equals("")) {
						throw new WTException(numberStr + "必须为数字！");
					}
				}
				if (wfactivity1.getName().equals("集团商务填写价格")) {
					String emptyStr = "";
					String numberStr = "";
					HashMap aMap = nmcommandbean.getComboBox();
					HashMap textMap = nmcommandbean.getTextArea();
					price = (String) textMap.get("CustActVarpriceCustActVar");

					if (null == price || price.trim().equals("")) {
						// throw new WTException("价格字段不能为空，请填写!");
						emptyStr = emptyStr + "价格字段" + ",";
					} else {
						if (!PartCommands.isDecimal(price)) {
							numberStr = numberStr + "价格字段" + ",";
						}
					}
					if (!emptyStr.equals("")) {
						throw new WTException(emptyStr + "不能为空！");
					}
					if (!numberStr.equals("")) {
						throw new WTException(numberStr + "必须为数字！");
					}
				}
			}
		}
		// 执行下面complete方法，会首先执行检测角色的参与者是否具备，若不具备就会报异常，就不会执行我们客制化的代码，使用try
		// finally的
		// 的好处是无论有无异常报出皆可执行我们客制化的代码
		try {
			NmOid nmoid = nmcommandbean.getPageOid();
			reviewObjss = PartWorkflowUtil.getReviewObjs(nmoid.toString());
			service.complete(nmcommandbean, getParams(nmcommandbean));
		} finally {
			// add by wzhou for reject start
			setCompelte(nmcommandbean);
			System.out.println("+++++++++++custWfAugment:" + custWfAugment);
			// add by wzhou for reject end
			if (custWfAugment) {
				NmOid nmoid = nmcommandbean.getPrimaryOid();
				WorkItem workitem2 = (WorkItem) nmoid.getRef();
				ProcessData workitemProcessData = workitem2.getContext();
				WfActivity wfactivity = (WfActivity) workitem2.getSource().getObject();
				ProcessData wfactivityProcessData = wfactivity.getContext();
				String onlyString = (String) wfactivityProcessData.getValue("OnlyString");
				System.out.println("OnlyString.>>>>>>>>>>>>>>>>>>" + onlyString);
				WfProcess wfprocess = wfactivity.getParentProcess();
				ProcessData wfprocessProcessData = wfprocess.getContext();
				String[] onlyStringArray = onlyString.split(";;;qqq");
				System.out.println("onlyStringArray  length  is>>>>>>>>>>" + onlyStringArray.length);
				for (int i = 0; i < onlyStringArray.length; i++) {
					String string = onlyStringArray[i];
					System.out.println("onlyStringArray   index  (" + i + ")===============" + string);
				}
				if (onlyStringArray != null) {
					for (int i = 0; i < onlyStringArray.length; i++) {
						if (!onlyStringArray[i].equals("")) {
							Object onlyStringObj = wfprocessProcessData.getValue(onlyStringArray[i]);

							if (onlyStringObj == null) {
								System.out.println("for xun huan li mian onlyStringObj == null");
							}

							Boolean onlyStringValue = (Boolean) onlyStringObj;

							System.out.println("for xun huan li mian onlyStringValue = " + onlyStringValue);

							if (onlyStringValue) {
								System.out.println("for xun huan li mian===========" + onlyStringArray[i]);
								workitemProcessData.setValue(onlyStringArray[i], true);
								wfactivityProcessData.setValue(onlyStringArray[i], true);
							}
						}
					}
				}
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
				wfactivity.setContext(wfactivityProcessData);
				wt.fc.PersistenceHelper.manager.save(wfactivity);
				workitem2.setContext(workitemProcessData);
				wt.fc.PersistenceHelper.manager.save(workitem2);
				// System.out.println("complete: approve
				// ="+wfactivityProcessData.getValue("approve")+"audit"+wfactivityProcessData.getValue("audit"));
			} else {
				NmOid nmoid = nmcommandbean.getPrimaryOid();
				WorkItem workitem2 = (WorkItem) nmoid.getRef();
				ProcessData workitemProcessData = workitem2.getContext();
				WfActivity wfactivity1 = (WfActivity) workitem2.getSource().getObject();
				System.out.println("当前活动的名称：" + wfactivity1.getName());
				if (flag1) {
					if (wfactivity1.getName().equals("原材料审核信息输入")
							|| (wfactivity1.getName().equals("半成品审核信息输入") && typeflag)
							|| (wfactivity1.getName().equals("二供物料审核信息输入") && typeflag)
							|| wfactivity1.getName().equals("版本进阶物料审核信息输入")) {
						WfProcess wfprocess = wfactivity1.getParentProcess();
						ProcessData wfprocessProcessData = wfprocess.getContext();
						System.out.println("###############wfprocess name :" + wfprocess.getName());
						if (null == wfprocessProcessData) {
							System.out.println("##########wfprocessProcessData is  null");
						} else {
							System.out.println("##########wfprocessProcessData is  not null");
						}

						wfprocessProcessData.setValue("supplier", supplier);
						wfprocessProcessData.setValue("price", price);
						wfprocessProcessData.setValue("currency", currency);
						wfprocessProcessData.setValue("delivery", delivery);
						wfprocessProcessData.setValue("landt", landt);
						wfprocessProcessData.setValue("order", order);
						wfprocessProcessData.setValue("minpackage", minpackage);

						wfprocess.setContext(wfprocessProcessData);
						wt.fc.PersistenceHelper.manager.save(wfprocess);

					}
					if ((wfactivity1.getName().equals("二供物料审核信息输入") || wfactivity1.getName().equals("半成品审核信息输入"))
							&& (!typeflag) && (!typeflag1)) {
						WfProcess wfprocess = wfactivity1.getParentProcess();
						ProcessData wfprocessProcessData = wfprocess.getContext();
						System.out.println("###############wfprocess name :" + wfprocess.getName());
						if (null == wfprocessProcessData) {
							System.out.println("##########wfprocessProcessData is  null");
						} else {
							System.out.println("##########wfprocessProcessData is  not null");
						}

						wfprocessProcessData.setValue("price", price);

						wfprocess.setContext(wfprocessProcessData);
						wt.fc.PersistenceHelper.manager.save(wfprocess);

					}
				}
			}
		}

		httpsession.removeAttribute("CHECKED_USERS");
		httpsession.removeAttribute("isPaged");

		nmurl.setType("homepage");
		// nmurl.setAction("list");
		// nmurl.setOid(null);
		try {
			String s4 = (String) nmcommandbean.getSessionBean().getStorage().get("tk");
			if (s4 == null || s4 != null && !s4.equals("null")) {
				s4 = httpsession.getAttribute("tk").toString();
				httpsession.removeAttribute("tk");
			} else if (s4.equals("prj")) {
				nmurl.setAction("listProjectAssignments");
				nmurl.setOid(new NmOid("project", (ObjectIdentifier) nmcommandbean.getContainerRef().getKey()));
			} else if (s4.equals("prd")) {
				nmurl.setAction("listProductAssignments");
				nmurl.setOid(new NmOid("object", (ObjectIdentifier) nmcommandbean.getContainerRef().getKey()));
			} else if (s4.equals("lib")) {
				nmurl.setAction("listLibraryAssignments");
				nmurl.setOid(new NmOid("object", (ObjectIdentifier) nmcommandbean.getContainerRef().getKey()));
			} else if (s4.equals("pln")) {
				if (nmcommandbean.getContainer().getConceptualClassname()
						.equalsIgnoreCase("wt.projmgmt.admin.Project2")) {
					nmurl.setType("project");
					nmurl.setAction("view_plan");
					nmurl.setOid(new NmOid("project", (ObjectIdentifier) nmcommandbean.getContainerRef().getKey()));
				}
			} else if (s4.equals("dtl")) {
				nmurl.setType("object");
				nmurl.setAction("view");
				String s7 = (String) nmcommandbean.getSessionBean().getStorage().get("task-type");
				if (s7 == null || s7 != null && !s7.equals("null")) {
					s7 = httpsession.getAttribute("task-type").toString();
					httpsession.removeAttribute("task-type");
				}
				String s8 = (String) nmcommandbean.getSessionBean().getStorage().get("task-oid");
				if (s8 == null || s8 != null && !s8.equals("null")) {
					s8 = httpsession.getAttribute("task-oid").toString();
					httpsession.removeAttribute("task-oid");
				}
				if ((nmcommandbean.getActionOid().getRef() instanceof WorkItem) && s7.equals("workflow")) {
					WorkItem workitem = (WorkItem) nmcommandbean.getActionOid().getRef();
					if (workitem != null && workitem.getPrimaryBusinessObject() != null) {
						nmurl.setOid(new NmOid(workitem.getPrimaryBusinessObject().getObject()));
					} else {
						nmurl.setOid(new NmOid(s8));
					}
				} else {
					nmurl.setOid(new NmOid(s8));
				}
			} else if (s4.equals("orv")) {
				nmurl.setType("netmarkets");
				nmurl.setAction("view");
				nmurl.setOid(null);
			} else if (s4.equals("viewDocument")) {
				String s6 = (String) nmcommandbean.getSessionBean().getStorage().get("task-oid");
				if (s6 == null || s6 != null && !s6.equals("null")) {
					s6 = httpsession.getAttribute("task-oid").toString();
					httpsession.removeAttribute("task-oid");
				}
				ConcurrentHashMap concurrenthashmap = nmcommandbean.getSessionBean().getStorage();
				nmurl.setAction("view");
				nmurl.setType("object");
				nmurl.setOid(new NmOid(s6));
			}
		} catch (NullPointerException nullpointerexception) {
			nmurl.setType("work");
			nmurl.setAction("list");
			nmurl.setOid(null);
			if (logger.isDebugEnabled()) {
				logger.debug(nullpointerexception.getLocalizedMessage(), nullpointerexception);
			}
		}
		FormResult formresult = new FormResult(FormProcessingStatus.SUCCESS);
		formresult.setNextAction(FormResultAction.FORWARD);
		formresult.setForcedUrl(nmurl.toString2(nmcommandbean.getUrlFactoryBean()));
		if (VERBOSE)
			System.out.println("<<== CmWorkItemCommands.complete（）");
		return formresult;
	}

	public static FormResult save(NmCommandBean nmcommandbean) throws WTException {
		FormResult formresult = new FormResult(FormProcessingStatus.SUCCESS);
		if (VERBOSE)
			System.out.println("=> CmWorkItemCommands.save");
		Enumeration enumeration = nmcommandbean.getRequest().getParameterNames();

		// customization NO.4 begin
		String participants = "";
		boolean custWfAugment = false;
		// customization NO.4 end
		do {
			if (!enumeration.hasMoreElements()) {
				break;
			}
			String s = (String) enumeration.nextElement();
			String s1 = NmCommandBean.convert(s);
			if (logger.isTraceEnabled()) {
				logger.trace((new StringBuilder()).append("=> NmWorkItemCommands.save: ").append(s1).append(", ")
						.append(nmcommandbean.getTextParameter(s)).toString());
			}
			if (s1.indexOf("CustActVar") >= 0 && s1.lastIndexOf("old") == -1) {
				int i = s1.indexOf("CustActVar") + "CustActVar".length();
				int j = s1.lastIndexOf("CustActVar");
				nmcommandbean.getMap().put(s1.substring(i, j), nmcommandbean.getTextParameter(s));
			}
			if (s1.indexOf("___comments___") >= 0 && !s1.endsWith("___old")) {
				nmcommandbean.getMap().put("comments", nmcommandbean.getTextParameter(s));
			}
			if (s1.indexOf("___voteAction___") >= 0 && !s1.endsWith("___old")) {
				nmcommandbean.getMap().put("voteAction", nmcommandbean.getTextParameter(s));
			}

			// customization NO.5 begin
			if (s1.equals("RolesParticipants")) {
				System.out.println("=> CmWorkItemCommands.complete: enter getting RolesParticipants...");
				participants = nmcommandbean.getTextParameter(s);
				custWfAugment = true;
			}
			// customization NO.5 end
		} while (true);

		// customization NO.6 begin
		if (custWfAugment)
			custService.save(nmcommandbean, participants);
		// customization NO.6 end

		service.save(nmcommandbean, getParams(nmcommandbean));
		if (custWfAugment) {
			NmOid nmoid = nmcommandbean.getPrimaryOid();
			WorkItem workitem = (WorkItem) nmoid.getRef();
			ProcessData workitemProcessData = workitem.getContext();
			System.out.println("workitem:2222222" + workitem.getIdentity());
			WfActivity wfactivity = (WfActivity) workitem.getSource().getObject();
			ProcessData wfactivityProcessData = wfactivity.getContext();
			String onlyString = (String) wfactivityProcessData.getValue("OnlyString");
			WfProcess wfprocess = wfactivity.getParentProcess();
			ProcessData wfprocessProcessData = wfprocess.getContext();
			String[] onlyStringArray = onlyString.split(";;;qqq");
			for (int i = 0; i < onlyStringArray.length; i++) {
				if ((Boolean) wfprocessProcessData.getValue(onlyStringArray[i])) {
					workitemProcessData.setValue(onlyStringArray[i], true);
					wfactivityProcessData.setValue(onlyStringArray[i], true);
				}
			}
			wfactivity.setContext(wfactivityProcessData);
			wt.fc.PersistenceHelper.manager.save(wfactivity);
			workitem.setContext(workitemProcessData);
			wt.fc.PersistenceHelper.manager.save(workitem);
			// 获取WfActivity "OnlyString"变量；
			// 获取流程的对应的变量值(WfProcess)；true 必走环节，重新刷新值；否则为不走的流程环节，则无需处理；
			// 重新更新WfActivity对应变量值（这里要排除可选流程环节对应的变量）
			// 循环onlystring，全局变量原值true，活动节点的属性值也设置为true
			// 设置context，保存wfactivityprocessData.
		}
		NmURL nmurl = new NmURL();
		nmurl.setType("work");
		nmurl.setAction("list");
		nmurl.setOid(null);
		HttpSession httpsession = nmcommandbean.getRequest().getSession();
		try {
			String s2 = (String) nmcommandbean.getSessionBean().getStorage().get("tk");
			if (s2 == null || s2 != null && !s2.equals("null")) {
				s2 = httpsession.getAttribute("tk").toString();
				httpsession.removeAttribute("tk");
			}
			if (s2.equals("prj")) {
				nmurl.setAction("listProject");
				nmurl.setOid(new NmOid("project", (ObjectIdentifier) nmcommandbean.getContainerRef().getKey()));
			} else if (s2.equals("pln")) {
				nmurl.setType("project");
				nmurl.setAction("view_plan");
				nmurl.setOid(new NmOid("project", (ObjectIdentifier) nmcommandbean.getContainerRef().getKey()));
			} else if (s2.equals("dtl")) {
				String s3 = (String) nmcommandbean.getSessionBean().getStorage().get("task-type");
				if (s3 == null || s3 != null && !s3.equals("null")) {
					s3 = httpsession.getAttribute("task-type").toString();
					httpsession.removeAttribute("task-type");
				}
				String s4 = (String) nmcommandbean.getSessionBean().getStorage().get("task-oid");
				if (s4 == null || s4 != null && !s4.equals("null")) {
					s4 = httpsession.getAttribute("task-oid").toString();
					httpsession.removeAttribute("task-oid");
				}
				nmurl.setType(s3);
				nmurl.setOid(new NmOid(s4));
				nmurl.setAction("view");
			} else if (s2.equals("orv")) {
				nmurl.setType("netmarkets");
				nmurl.setAction("view");
				nmurl.setOid(null);
			} else if (s2.equals("viewDocument")) {
				ConcurrentHashMap concurrenthashmap = nmcommandbean.getSessionBean().getStorage();
				String s5 = (String) nmcommandbean.getSessionBean().getStorage().get("task-oid");
				if (s5 == null || s5 != null && !s5.equals("null")) {
					s5 = httpsession.getAttribute("task-oid").toString();
					httpsession.removeAttribute("task-oid");
				}
				nmurl.setAction("view");
				nmurl.setType("object");
				nmurl.setOid(new NmOid(s5));
			}
		} catch (NullPointerException nullpointerexception) {
			nmurl.setType("work");
			nmurl.setAction("list");
			nmurl.setOid(null);
			if (logger.isDebugEnabled()) {
				logger.debug(nullpointerexception.getLocalizedMessage(), nullpointerexception);
			}
		}
		formresult.setNextAction(FormResultAction.NONE);
		if (VERBOSE) {
			if (VERBOSE)
				System.out.println("<<==CmWorkItemCommands.save");
		}
		return formresult;
	}

	private static HashMap getParams(NmCommandBean nmcommandbean) {
		HashMap hashmap = new HashMap(12);
		HttpServletRequest httpservletrequest = nmcommandbean.getRequest();
		String s;
		for (Enumeration enumeration = httpservletrequest.getParameterNames(); enumeration
				.hasMoreElements(); addParam(hashmap, httpservletrequest, s, nmcommandbean)) {
			s = (String) enumeration.nextElement();
		}

		return hashmap;
	}

	private static void addParam(HashMap hashmap, HttpServletRequest httpservletrequest, String s,
			NmCommandBean nmcommandbean) {
		String s1 = nmcommandbean.getTextParameter(s);
		if (s1 == null) {
			s1 = "";
		}
		hashmap.put(s, s1);
	}

	private static Team clearTeamRole(Team team, String rolename) throws WTException {
		Enumeration enums = getRoleEnumeration(team, rolename);
		while (enums != null && enums.hasMoreElements()) {
			wt.org.WTPrincipal wtp = ((wt.org.WTPrincipalReference) enums.nextElement()).getPrincipal();
			boolean doDelete = deleteProcessRoleHolder(team, rolename, wtp);
		}
		return team;
	}

	private static java.util.Enumeration getRoleEnumeration(wt.team.Team team, String rolename) throws WTException {
		if (rolename == null || rolename.length() == 0)
			return null;
		wt.project.Role role = (wt.project.Role) (wt.project.Role.toRole(rolename));
		return team.getPrincipalTarget(role);
	}

	private static boolean deleteProcessRoleHolder(Team team, String rolename, wt.org.WTPrincipal prin) {
		boolean flag = true;
		try {
			wt.project.Role role = (wt.project.Role) (wt.project.Role.toRole(rolename));
			team.deletePrincipalTarget(role, prin);
		} catch (Exception e) {
			System.out.println("	deleteProcessRoleHolder : error");
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	static {
		logger = LogR.getLogger("com.ptc.netmarkets.work");
		try {
			WTProperties wtproperties = WTProperties.getLocalProperties();
			VERBOSE = wtproperties.getProperty("ext.generic.wfaugment.verbose", false);
		} catch (Throwable throwable) {
			throwable.printStackTrace(System.err);
			throw new ExceptionInInitializerError(throwable);
		}
	}

	public static void testComments(NmCommandBean paramNmCommandBean) throws WTException {
		System.out.println("====testComments start===");
		boolean flag = isRefuse(paramNmCommandBean);
		if (flag) {
			HashMap map = paramNmCommandBean.getTextArea();
			String text = (String) map.get("comments");
			System.out.println(">>>>>>>>>>>>text" + text.trim().equals(""));
			if (null == text || text.trim().equals("")) {
				System.out.println(">>>>>>>>>>>>>>备注栏");
				throw new WTException("请填写备注栏！！");
			}
		}
		System.out.println("====testComments end===");

	}

	/**
	 * 填写半成品正式编码
	 * 
	 * @param paramNmCommandBean
	 * @throws WTException
	 */
	public static void editNumber(NmCommandBean paramNmCommandBean) throws WTException {
		System.out.println("===============editNumber==========start");
		HttpServletRequest request = paramNmCommandBean.getRequest();
		WorkItem workItem = (WorkItem) paramNmCommandBean.getActionOid().getRef();
		// 获取活动
		WfActivity activity = (WfActivity) workItem.getSource().getObject();
		// 获取活动名称
		String activityname = activity.getName();
		// 获取活动id
		String oid = paramNmCommandBean.getActionOid().toString();
		// 获取工作流
		WfProcess process = WorkFlowUtil.GetWfProcess(oid);
		// 获取pbo
		Object pbo = workItem.getPrimaryBusinessObject().getObject();
		System.out.println("============editNumber enter======process name:"+process.getName()+"===activityname:"+activityname);
		
		if (process.getName().indexOf("配套物料申请流程")!=-1 && "半成品审核(BOM工程师)".equals(activityname.toString())) {
			System.out.println("============editNumber enter======");
			WTChangeOrder2 eco = null;
			if (pbo instanceof WTChangeOrder2) {
				eco = (WTChangeOrder2) pbo;
			}
			if (eco != null) {
				// 设置流程变量
				setProcessParams(eco, process, request);
			}
		}
		System.out.println("===============editNumber==========end");
	}

	/**
	 * 设置正式编码变量 格式如下： { "C1":"", "C2","", "C3","" "C5":"", ... }
	 * 
	 * @param eco
	 * @param process
	 * @param request
	 */
	public static void setProcessParams(WTChangeOrder2 eco, WfProcess process, HttpServletRequest request) {
		System.out.println("============setProcessParams enter======");
		if (process != null && eco != null) {
			String data = "";
			JSONObject object = new JSONObject();
			ProcessData processData = process.getContext();
			try {
				QueryResult queryResultECA = ChangeHelper2.service.getChangeActivities(eco);
				if (queryResultECA != null) {
					while (queryResultECA.hasMoreElements()) {
						WTChangeActivity2 eca = (WTChangeActivity2) queryResultECA.nextElement(); // 获取ECA
						System.out.println("============setProcessParams eca======"+eca.getName()+"---number:"+eca.getNumber());
						if (eca != null) {
							// 受影响对象
							QueryResult queryResultPart = ChangeHelper2.service.getChangeablesBefore(eca);
							if (queryResultPart != null) {
								while (queryResultPart.hasMoreElements()) {
									Changeable2 changeable = (Changeable2) queryResultPart.nextElement();
									if (changeable != null && changeable instanceof WTPart) {
										WTPart part = (WTPart) changeable;
										String Type = (String) IBAUtil.getIBAValue(part, "SemiFinishedGoodType");
										System.out.println("===Typevalue:" + Type);
										if (!StringUtil.isNullOrEmpty(Type)) {
											String value = request.getParameter(Type);
											System.out.println("====value:" + value);
											// 若页面存在对应的值 则放在变量中 否则提示分类未填写
											if (!StringUtil.isNullOrEmpty(value)) {
												try {
													object.put(Type, value);
												} catch (JSONException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
											} else {
												throw new WTException(Type + "的正式编号未填写");
											}
										}

									}
								}
							}
						}
					}
				}
				data = object.toString();
				System.out.println("======data:"+data);
				System.out.println("======processData number before :"+processData.getValue("正式编码"));
				
				
				//WfVariable VariableMainType = process.getContext().getVariable("正式编码");
				//VariableMainType.setValue(data);
				
				processData.setValue("正式编码", data);
				System.out.println("======data:" + data);

				processData.setValue("isSuperEdit", data);
				process.setContext(processData);
				wt.fc.PersistenceHelper.manager.save(process);
				System.out.println("======processData number after:"+processData.getValue("正式编码"));
				wt.fc.PersistenceHelper.manager.refresh(process);
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	public static void setCompelte(NmCommandBean paramNmCommandBean) throws WTException {
		// customization NO.1 begin
		// 获取工作流流程
		WfProcess process = null;
		NmOid nmoid = (NmOid) paramNmCommandBean.getPrimaryOid();

		String oid = (String) nmoid.getOid().toString();
		ReferenceFactory rf = new ReferenceFactory();
		WorkItem item = (WorkItem) rf.getReference(oid).getObject();
		Persistable pbo = item.getPrimaryBusinessObject().getObject();
		try {
			NmOid nmoids = NmOid.newNmOid(PersistenceHelper.getObjectIdentifier(pbo));
			QueryResult qr = NmWorkflowHelper.service.getRoutingHistoryData(nmoids);
			while (qr.hasMoreElements()) {
				process = (WfProcess) qr.nextElement();
				String state = process.getState().toString();
				if ("OPEN_RUNNING".equals(state)) {
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 获取用户的投票结果
		WTCollection auditCol = WfEngineHelper.service.getVotingEvents(process, null, null, null);
		Iterator auditEvents = auditCol.persistableIterator();
		String processName = process.getName();
		boolean flag = processName.equals("文档签审流程");
		while (auditEvents.hasNext()) {
			WfVotingEventAudit audit = (WfVotingEventAudit) auditEvents.next();
			// System.out.println("Transition Expression: User vote = " +
			// audit.getEventList().toString());
			// 此处判断一下用户的投票结果是否是驳回

			System.out.println(">>>>>>>>>audit.getEventList().toString():" + audit.getEventList().toString());
			if ("[驳回]".equals(audit.getEventList().toString())) {

				WfState wfState = process.getState();
				System.out.println("PROCESS STATE = " + wfState.toString());
				WfAssignedActivity wfAssignedActivity = null;
				if (wfState.toString().equals("OPEN_RUNNING")) {
					// 搜索工作流流程下的所有活动
					QuerySpec wfAssignedActivityQuerySpec = new QuerySpec(WfAssignedActivity.class);
					SearchCondition sc = new SearchCondition(WfAssignedActivity.class, "state", SearchCondition.EQUAL,
							"OPEN_RUNNING");
					wfAssignedActivityQuerySpec.appendSearchCondition(sc);
					sc = new SearchCondition(WfAssignedActivity.class, "parentProcessRef.key", "=",
							PersistenceHelper.getObjectIdentifier(process));
					wfAssignedActivityQuerySpec.appendAnd();
					wfAssignedActivityQuerySpec.appendSearchCondition(sc);
					QueryResult qr = PersistenceHelper.manager.find(wfAssignedActivityQuerySpec);
					while (qr.hasMoreElements()) {
						wfAssignedActivity = (WfAssignedActivity) qr.nextElement();
						// 获得活动的名字
						System.out.println("wfactivityName=" + wfAssignedActivity.getName());
						try {
							Team team = TeamHelper.service.getTeam(process);
							if (team == null)
								return;
							// 得到活动参与者DESIGNER下的用户
							Role role = Role.toRole("Signer");
							Enumeration participants = team.getPrincipalTarget(role);
							System.out.println(">>>>>>>>>>>>>>>>participants:" + participants.hasMoreElements());
							while (participants.hasMoreElements()) {
								WTPrincipalReference principalRef = (WTPrincipalReference) participants.nextElement();
								if (principalRef == null || principalRef.isDisabled())
									continue;
								WTPrincipal principal = principalRef.getPrincipal();
								System.out.println(">>>>>>>>>>>>>>>>>>>>>>user:" + principal.getName());
								WTPrincipal loginPrincipal = SessionHelper.manager.getPrincipal();

								if (!(loginPrincipal.getName().equals(principal.getName()))) {
									// 指定pbo和用户的任务
									Enumeration userWorkItems = WorkflowHelper.service.getWorkItems((WTObject) pbo,
											principal);
									while (userWorkItems.hasMoreElements()) {
										WorkItem workItem = (WorkItem) userWorkItems.nextElement();
										// 筛选未完成
										if (!workItem.isComplete()) {
											WfActivity currentActivityName = (WfActivity) workItem.getSource()
													.getObject();
											System.out.println(">>>>>>>>>>>>>>>>>>wfActivity name="
													+ currentActivityName.getName());
											// 活动名相同
											if (currentActivityName.getName().equals("BOM审核")
													|| currentActivityName.getName().equals("原材料审核(BOM工程师)")
													|| currentActivityName.getName().equals("各部门主管和FAE审核")
													|| currentActivityName.getName().equals("PM/PI/部门主管会签")
													|| currentActivityName.getName().equals("会签")
													|| currentActivityName.getName().equals("图纸审核") || flag) {
												// System.out.println("完成指定pbo("
												// + pbo + ")里指定用户(" +
												// pricipal.getName() +
												// ")的指定活动名(" + activityName +
												// ")的任务");
												WTPrincipalReference userref = workItem.getOwnership().getOwner();
												System.out.println(
														">>>>>>>>>>>>>>>>>>>>>>>>>>userref:" + userref.getName());
												System.out.println(
														">>>>>>>>>>>>>>>>>>>>>>>>>>userref.getPrincipal().getName():"
																+ userref.getPrincipal().getName());
												// 任务执行人和指定用户相同o
												if (userref.getName().equals(principal.getName())) {
													System.out.println(">>>>>>>>>>>>>>>>>>>>.true ");
													WorkflowHelper.service.workComplete(workItem, userref, null);
												}
											}
										}
									}

								}
							}
						} catch (WTException e) {
							e.printStackTrace();
						}

					}

				}

			}
			audit.getEventList().clear();
			break;
		}

		// customization NO.1 end

	}

	public static void setProcessVariable(NmCommandBean nmcommandbean) throws WTException {
		// //add buy wzhou 检查供应商信息是否填写，并且设置到流程变量中
		System.out.println(">>>>>>>>>>>>>    setProcessVariable()    start");
		NmOid nmoid1 = nmcommandbean.getPrimaryOid();
		WorkItem workitem2 = (WorkItem) nmoid1.getRef();
		// ProcessData workitemProcessData = workitem2.getContext();
		wt.fc.Persistable pbo = workitem2.getPrimaryBusinessObject().getObject();
		boolean typeflag = true;
		boolean typeflag1 = true;
		typeflag = ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "CF")
				|| ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "RawMaterial")
				|| ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "Polarizer")
				|| ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "PhantomPolarizer");
		typeflag1 = ext.tianma.part.PartCommands.isObjectType((wt.fc.WTObject) pbo, "C4");
		WfActivity wfactivity1 = (WfActivity) workitem2.getSource().getObject();
		System.out.println("当前活动的名称：" + wfactivity1.getName());
		if (wfactivity1.getName().equals("原材料审核信息输入") || (wfactivity1.getName().equals("半成品审核信息输入") && typeflag)
				|| (wfactivity1.getName().equals("二供物料审核信息输入") && typeflag)) {
			// WfProcess wfprocess = wfactivity1.getParentProcess();
			// ProcessData wfprocessProcessData = wfprocess.getContext();

			HashMap aMap = nmcommandbean.getComboBox();
			HashMap textMap = nmcommandbean.getText();
			String supplier = (String) textMap.get("supplier");
			if (null == supplier || supplier.trim().equals("")) {
				throw new WTException("供应商字段不能为空，请填写!");
			}
			String price = (String) textMap.get("price");
			if (null == price || price.trim().equals("")) {
				throw new WTException("价格字段不能为空，请填写!");
			}
			String currency = null;
			ArrayList<String> currencyList = (ArrayList<String>) aMap.get("currency");
			if (currencyList != null && currencyList.size() == 1) {
				currency = currencyList.get(0).trim();
			}
			if (null == currency || currency.trim().equals("")) {
				throw new WTException("币种字段不能为空，请填写!");
			}

			String delivery = (String) textMap.get("delivery");
			if (null == delivery || delivery.trim().equals("")) {
				throw new WTException("日交货能力字段不能为空，请填写!");
			}

			String landt = (String) textMap.get("landt");
			if (null == landt || landt.trim().equals("")) {
				throw new WTException("L/T字段不能为空，请填写!");
			}

			String order = (String) textMap.get("order");
			if (null == order || order.trim().equals("")) {
				throw new WTException("最小订货量字段不能为空，请填写!");
			}

			String minpackage = (String) textMap.get("minpackage");
			if (null == minpackage || minpackage.trim().equals("")) {
				throw new WTException("最小包装字段不能为空，请填写!");
			}

			System.out.println("供应商：" + supplier);
			System.out.println("价格：" + price);
			System.out.println("币种：" + currency);
			System.out.println("日交货能力：" + delivery);
			System.out.println("L/T：" + landt);
			System.out.println("最小订货量：" + order);
			System.out.println("最小包装：" + minpackage);

			/*
			 * workitemProcessData.setValue("supplier", supplier);
			 * workitemProcessData.setValue("price", price);
			 * workitemProcessData.setValue("currency", currency);
			 * workitemProcessData.setValue("delivery", delivery);
			 * workitemProcessData.setValue("landt", landt);
			 * workitemProcessData.setValue("order", order);
			 * workitemProcessData.setValue("minpackage", minpackage);
			 * 
			 * workitem2.setContext(workitemProcessData);
			 * wt.fc.PersistenceHelper.manager.save(workitem2);
			 */

		}
		if ((wfactivity1.getName().equals("半成品审核信息输入") || wfactivity1.getName().equals("二供物料审核信息输入")) && (!typeflag)
				&& (!typeflag1)) {
			HashMap aMap = nmcommandbean.getComboBox();
			HashMap textMap = nmcommandbean.getText();
			String price = (String) textMap.get("price");
			System.out.println("价格：" + price);
			if (null == price || price.trim().equals("")) {
				throw new WTException("价格字段不能为空，请填写!");
			}
		}
		System.out.println("<<<<<<<<<<<    setProcessVariable()    end");
	}

	/**
	 * 
	 * @param paramNmCommandBean
	 * @return
	 * @throws WTException
	 */
	public static boolean isReject(NmCommandBean paramNmCommandBean) throws WTException {
		HashMap map = paramNmCommandBean.getRadio();
		String value = (String) map.get("WfUserEvent0");

		System.out.println("is reject >>>>>>>>>    当前路由value：" + value);
		if (null != value && value.equals("通过")) {
			return true;
		}
		return false;
	}

	public static boolean isRefuse(NmCommandBean paramNmCommandBean) throws WTException {
		HashMap map = paramNmCommandBean.getRadio();
		String value = (String) map.get("WfUserEvent0");

		System.out.println("is reject >>>>>>>>>    当前路由value：" + value);
		if (null != value && (value.equals("驳回") || value.equals("驳回返回"))) {
			return true;
		}
		return false;
	}

	/**
	 * 图文档借阅相关节点提交业务 lilin
	 * 
	 * @param cb
	 * @throws WTException
	 */

	public static void doDrawingPDF(NmCommandBean cb) throws WTException {
		System.out.println("................doDrawingPDF go to start................");
		// ****begin add by lilin 图文档借阅相关节点提交业务 2018-11-19 11:57:35
		boolean flagAccess = SessionServerHelper.manager.setAccessEnforced(false);
		// 忽略权限
		try {
			HttpServletRequest request = cb.getRequest();
			WorkItem workItem = (WorkItem) cb.getActionOid().getRef();
			// 获取活动
			WfActivity activity = (WfActivity) workItem.getSource().getObject();
			// 获取活动名称
			String activityname = activity.getName();
			// 获取活动id
			String oid = cb.getActionOid().toString();
			// 获取工作流
			WfProcess process = WorkFlowUtil.GetWfProcess(oid);
			// 获取pbo
			// Object pbo = workItem.getPrimaryBusinessObject().getObject();
			if ("业务上级审核".equals(activityname.toString())) {

				String dayNum = request.getParameter("day");
				if (!"".equals(dayNum)) {
					ProcessData processData = process.getContext();
					String version = (String) processData.getValue("versionName");
					WTObject wtObject = BorrowWorkflowUtil.getPBO(process);
					WTDocument doc = null;
					if (wtObject != null && wtObject instanceof WTDocument) {
						doc = (WTDocument) wtObject;
					}
					if (doc != null) {
						BorrowUtil.updateDrawingBorrowDay(dayNum, doc.getNumber(), process.getCreator().getName(),
								version);// 根据版本、编号、用户更新借阅天数
						processData.setValue("isSuperEdit", false);
						process.setContext(processData);
						wt.fc.PersistenceHelper.manager.save(process);
					}
				}
			} else if ("修改者审核".equals(activityname.toString())) {
				String newDocVer = request.getParameter("docVer");// 指定版本
				String dayNum = "";
				ProcessData processData = process.getContext();
				String oldDocVer = (String) processData.getValue("versionName");
				if (!"".equals(newDocVer)) {
					WTObject wtObject = BorrowWorkflowUtil.getPBO(process);
					WTDocument doc = null;
					if (wtObject != null && wtObject instanceof WTDocument) {
						doc = (WTDocument) wtObject;
					}
					if (doc != null) {
						//获取指定被借阅版本的图档是否存在，如果存在，获取对应的天数
						List<DrawingsBorrowBean> Drawings = BorrowUtil.getDrawingBorrowByNumberAndName(doc.getNumber(),
								process.getCreator().getName(), oldDocVer);// 通过文档编号和人员，查询数据表
						if (Drawings.size() != 0) {
							for (int i = 0; i < Drawings.size(); i++) {
								DrawingsBorrowBean db = Drawings.get(i);
								String state = db.getBorrowState();
								if (BorrowUtil.REVIEW.equals(state)) {
									dayNum = db.getBorrowDate();
								}
							}
						}
//						System.out.println("...............借阅天数：" + Integer.parseInt(dayNum));
						
						HolidayUtil h = new HolidayUtil();
						// 设置时区
						// TimeZone tz = WTContext.getContext().getTimeZone();
						// TimeZone.setDefault(tz);
						Date beginTime = new Date();
						//使用Calendar.getInstance()不仅能获取当前的时间，还能指定需要获取的时间点
						Calendar c = Calendar.getInstance();
							//设置日历的时间为给定的日期 Date.
							c.setTime(beginTime);
							//对日期进行加借阅天数操作
							c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(dayNum));
							int year = c.get(Calendar.YEAR);
							boolean isExit = h.isCurrentYear(String.valueOf(year));
						if (isExit) {
							BorrowWorkflowUtil.updateDrawingBorrowVersionAndStateAndBorrowDate(
									// 更新借阅版本、状态和时间
									doc.getNumber(), process.getCreator().getName(), oldDocVer, newDocVer, dayNum,
									BorrowUtil.BORROW);
							processData.setValue("versionName", newDocVer);
							processData.setValue("isOwerEdit", false);
							process.setContext(processData);
							wt.fc.PersistenceHelper.manager.save(process);

						} else {
							throw new WTException("对不起，您可能会使用到 " + year + " 年的节假日数据，系统中暂不存在，请联系管理员维护数据！");
						}
					}
				}
			}
			// ****end add by lilin 图文档借阅相关节点提交业务 2018-11-19 11:57:35
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(flagAccess);
		}

	}

	
	/**
	 * 样品承认SQE审核节点
	 * @param nmcommandbean
	 * @throws WTException
	 */
	public static void uploadFiles(NmCommandBean nmcommandbean) throws WTException {
		System.out.println("----uploadFiles-----");
		HttpServletRequest request = nmcommandbean.getRequest();

		boolean flagAccess = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction trx = new Transaction();
		try {
			
			WorkItem workItem = (WorkItem) nmcommandbean.getActionOid().getRef();

			// 获取活动
			WfActivity activity = (WfActivity) workItem.getSource().getObject();
			// 获取活动名称
			String activityname = activity.getName();
			// 获取活动id
			String oid = nmcommandbean.getActionOid().toString();
			// 获取工作流
			WfProcess process = WorkFlowUtil.GetWfProcess(oid);
			// 获取pbo
			Object pbo = workItem.getPrimaryBusinessObject().getObject();
			//样品提交节点设置业务类型
			if ((process.getName().indexOf("样品承认及批准流程")!=-1) && "样品提交".equals(activityname.toString())) {
				String businessType = request.getParameter("businessType");
				System.out.println("------businessType------"+businessType);
				WfVariable appdoc = process.getContext().getVariable("appDoc");
				Object value = appdoc.getValue();
				if(value==null) {
					throw new WTException("任务不能完成：上传文档不能为空");
				} else if(StringUtil.isNullOrEmpty(businessType)) {
					throw new WTException("任务不能完成：请选择业务类型");
				}
				//为流程变量赋值
				WfVariable VariableMainType = process.getContext().getVariable("businessType");
				VariableMainType.setValue(businessType);
				wt.fc.PersistenceHelper.manager.save(process);
			}
			WTObject wtObject = WorkItemHelper.getPBO(process);
			if(wtObject != null && wtObject instanceof WTPart) {
				WTPart part = (WTPart) wtObject;
				String modifyTime = CommonPDMUtil.getModifyTime(part);
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date modifyDate = simpleDateFormat.parse(modifyTime);
				Date date = simpleDateFormat.parse("2020-03-03 00:00:00");
				if(modifyDate.before(date)) {
					
				}else {
			//SQE审核节点获取页面值并赋予流程变量
			trx.start();
			if ((process.getName().indexOf("样品承认及批准流程")!=-1) && "零件批准".equals(activityname.toString())) {
				Map<String, String> map = new HashMap<String, String>();
				
				WfVariable VariableMainType = process.getContext().getVariable("businessType");
		        String businessType = VariableMainType.getValue().toString();
				System.out.println("====businessType value====="+businessType);
				
				if("xxPart".equals(businessType)) {
					String radio0 = request.getParameter("radio0");
					map.put("radio0", radio0);
				} else if("gkPart".equals(businessType)) {
					String bt = request.getParameter("bt");
					String cs = request.getParameter("cs");
					String bcs = request.getParameter("bcs");
					System.out.println("---cn bcs:"+bcs);
					String b1t1 = request.getParameter("b1t1");
					String b1t2 = request.getParameter("b1t2");
					String b2t1 = request.getParameter("b2t1");
					String b2t2 = request.getParameter("b2t2");
					String radio2 = request.getParameter("radio2");
					String radio4 = request.getParameter("radio4");
					String radio5 = request.getParameter("radio5");
					String radio6 = request.getParameter("radio6");
					String radio7 = request.getParameter("radio7");
					String radio8 = request.getParameter("radio8");
					System.out.println("-----radio8:"+radio8);

					map.put("bt", bt);
					map.put("cs", cs);
					map.put("bcs", bcs);
					map.put("b1t1", b1t1);
					map.put("b1t2", b1t2);
					map.put("b2t1", b2t1);
					map.put("b2t2", b2t2);
					map.put("radio2", radio2);
					map.put("radio4", radio4);
					map.put("radio5", radio5);
					map.put("radio6", radio6);
					map.put("radio7", radio7);
					map.put("radio8", radio8);
				} else if("czPart".equals(businessType)) {
					String bt = request.getParameter("bt");
					String cs = request.getParameter("cs");
					String bcs = request.getParameter("bcs");
					String b1t1 = request.getParameter("b1t1");
					String b1t2 = request.getParameter("b1t2");
					String b2t1 = request.getParameter("b2t1");
					String b2t2 = request.getParameter("b2t2");
					String radio2 = request.getParameter("radio2");
					String radio4 = request.getParameter("radio4");
					String radio5 = request.getParameter("radio5");
					String radio6 = request.getParameter("radio6");
					String radio7 = request.getParameter("radio7");
					String radioD1 = request.getParameter("radioD1");
					String radioD2 = request.getParameter("radioD2");
					String radioD3 = request.getParameter("radioD3");

					map.put("bt", bt);
					map.put("cs", cs);
					map.put("bcs", bcs);
					map.put("b1t1", b1t1);
					map.put("b1t2", b1t2);
					map.put("b2t1", b2t1);
					map.put("b2t2", b2t2);
					map.put("radio2", radio2);
					map.put("radio4", radio4);
					map.put("radio5", radio5);
					map.put("radio6", radio6);
					map.put("radio7", radio7);
					map.put("radioD1", radioD1);
					map.put("radioD2", radioD2);
					map.put("radioD3", radioD3);
				}
				
				System.out.println("--完成map:"+map.toString());
				//获取页面选中的值并赋值到流程中
				Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
				while (iterator.hasNext()) {
					// 获得key
					Map.Entry<String, String> entry = iterator.next();
					String key = entry.getKey();
					String value = entry.getValue();
					System.out.println("----Ckey: " + key + ",Cvalue----:" + value);
					if(StringUtil.isNullOrEmpty(value) || "实际".equals(value) || "目标".equals(value) || "实际关闭率".equals(value)) {
						throw new WTException("任务不能完成：选项不能为空！");
					}
					judgeFolder(process,key,value);
					
					//为流程变量赋值
					WfVariable VariableMainType2 = process.getContext().getVariable(key);
					VariableMainType2.setValue(value);
					wt.fc.PersistenceHelper.manager.save (process);
					String ss = VariableMainType2.getValue().toString();
					System.out.println("-----ss:"+ss);
				}
				
				WfVariable VariableMainType3 = process.getContext().getVariable("isEdit");
				VariableMainType3.setValue(false);
				String ss3 = VariableMainType3.getValue().toString();
				System.out.println("-----ss3:"+ss3);
				process = (WfProcess)wt.fc.PersistenceHelper.manager.save(process);
				
				trx.commit();
				trx = null;	
			}
				}
			}
		}   catch (ObjectNoLongerExistsException | ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  finally {
			if (trx != null) {
				trx.rollback();
			}
			SessionServerHelper.manager.setAccessEnforced(flagAccess);
		}
	}
	
	public static void judgeFolder(WfProcess process, String key, String value) throws WTException {
		WfVariable VariableMainType = null;
		WfVariable VariableMainType2 = null;
		Object VariableValue = null;
		Object VariableValue2 = null;
		
		String radio = "";
		if("N".equals(value)&&(!"radio0".equals(key))) {
			if("radio2".equals(key)) {
				radio = "2";
			} else if("radio4".equals(key)) {
				radio = "4";
			} else if("radio5".equals(key)) {
				radio = "5";
			} else if("radio6".equals(key)) {
				radio = "6";
			} else if("radio7".equals(key)) {
				radio = "7";
			} else if("radio8".equals(key) || "radioD1".equals(key)) {
				radio = "8";
			} else if("radioD2".equals(key)) {
				radio = "9";
			} else if("radioD3".equals(key)) {
				radio = "10";
			}
			
			throw new WTException("任务不能完成：第" + radio +"选项不能为N！");
		} else if("radio0".equals(key)&&"Y".equals(value)) {
			VariableMainType = process.getContext().getVariable("radio01");
			VariableValue = VariableMainType.getValue();
			if(VariableValue == null) {
				throw new WTException("任务不能完成：请上传所需文档！");
			}
		} else if("radio2".equals(key)&&"Y".equals(value)) {
			VariableMainType = process.getContext().getVariable("radio21");
			VariableValue = VariableMainType.getValue();
			if(VariableValue == null) {
				throw new WTException("任务不能完成：请上传所需文档！");
			}
		} else if("radio4".equals(key)&&"Y".equals(value)) {
			VariableMainType = process.getContext().getVariable("radio42");
			VariableValue = VariableMainType.getValue();
			if(VariableValue==null) {
				throw new WTException("任务不能完成：请上传所需文档！");
			}
		} else if("radio8".equals(key)&&"Y".equals(value)) {
			VariableMainType = process.getContext().getVariable("radio81");
			VariableValue = VariableMainType.getValue();
			if(VariableValue == null) {
				throw new WTException("任务不能完成：请上传所需文档！");
			}
		} else if("radioD1".equals(key)&&"Y".equals(value)) {
			VariableMainType = process.getContext().getVariable("radioD11");
			VariableValue = VariableMainType.getValue();
			if(VariableValue == null) {
				throw new WTException("任务不能完成：请上传所需文档！");
			}
		} else if("radioD2".equals(key)&&"Y".equals(value)) {
			VariableMainType = process.getContext().getVariable("radioD21");
			VariableValue = VariableMainType.getValue();
			VariableMainType2 = process.getContext().getVariable("radioD22");
			VariableValue2 = VariableMainType2.getValue();
			if(VariableValue==null || VariableValue2==null) {
				throw new WTException("任务不能完成：请上传所需文档！");
			}
		} else if("radioD3".equals(key)&&"Y".equals(value)) {
			WfVariable partDoc = process.getContext().getVariable("partDoc");
			Object partDocValue = partDoc.getValue();
			
			VariableMainType = process.getContext().getVariable("radioD31");
			VariableValue = VariableMainType.getValue();
			VariableMainType2 = process.getContext().getVariable("radioD32");
			VariableValue2 = VariableMainType2.getValue();
			
			if(partDocValue!=null) {
				if(VariableValue2==null) {
					throw new WTException("任务不能完成：请上传所需文档！");
				}
			} else {
				if(VariableValue==null || VariableValue2==null) {
					throw new WTException("任务不能完成：请上传所需文档！");
				}
			}
			
		}
	}
	
}
